package com.ruoyi.stock2.utils;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.*;
import javax.mail.search.FlagTerm;

public class Receivemail {

    public static void main(String[] args) throws Exception {
        imaptest();
        //pop3test();
    }
    public static void pop3test() throws Exception {
        // 定义连接POP3服务器的属性信息
        String pop3Server = "pop.qq.com";
        String protocol = "imap";
        String username = "359642959@qq.com";
        String password = "zacmsfziegiebjei"; // QQ邮箱的SMTP的授权码，什么是授权码，它又是如何设置？

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", protocol); // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.imap.host", pop3Server); // 发件人的邮箱的 SMTP服务器地址

        // 获取连接
        Session session = Session.getInstance(props);
        session.setDebug(false);

        // 获取Store对象
        Store store = session.getStore(protocol);
        store.connect(pop3Server, username, password); // POP3服务器的登陆认证

        // 通过POP3协议获得Store对象调用这个方法时，邮件夹名称只能指定为"INBOX"
        Folder folder = store.getFolder("INBOX");// 获得用户的邮件帐户
        folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限

        Message[] messages = folder.getMessages();// 得到邮箱帐户中的所有邮件

        for (Message message : messages) {
            String subject = "";
            try {
                subject = message.getSubject();// 获得邮件主题
                Address from = (Address) message.getFrom()[0];// 获得发送者地址
                System.out.println("邮件的主题为: " + subject + "\t发件人地址为: " + from);
                System.out.println("邮件的内容为：");
                message.writeTo(System.out);// 输出邮件内容到控制台
            }catch (MessageRemovedException exception){
                exception.printStackTrace();
            }


        }

        folder.close(false);// 关闭邮件夹对象
        store.close(); // 关闭连接对象

    }
    public static void imaptest(){

        String user = "359642959@qq.com";// 邮箱的用户名

        String password = "shbvyxjrsfqubghj"; // 邮箱的密码

        Properties prop = System.getProperties();

        prop.put("mail.store.protocol", "imap");

        prop.put("mail.imap.host", "imap.qq.com");

        Session session = Session.getInstance(prop);

        int total = 0;
        Message [] messages = null;
        IMAPFolder folder = null;
        IMAPStore store = null;
        try {
            store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制，连接服务器
            store.connect(user, password);
            folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱
            folder.open(Folder.READ_WRITE);
            total = folder.getMessageCount();
            System.out.println("-----------------共有邮件：" + total + " 封--------------");
            System.out.println("未读邮件数：" + folder.getUnreadMessageCount());
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN),false));
        }catch (Exception e){

        }
        //从收件箱文件夹中获取看不见的邮件
        //Message [] messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN),false));
        //Message[] messages = folder.getMessages();
        //Message[] messages = folder.getMessages(folder.getMessageCount()-folder.getUnreadMessageCount()+1,folder.getMessageCount());


        for (Message message : messages) {
            try{
                System.out.println("发送时间：" + message.getSentDate());
                System.out.println("主题：" + message.getSubject());
                System.out.println("内容：" + message.getContent());
                //getAllMultipart(message);
                Flags flags = message.getFlags();
                if (flags.contains(Flags.Flag.SEEN))
                    System.out.println("这是一封已读邮件");
                else {
                    System.out.println("未读邮件");
                }
            }catch (Exception e){

            }
            //每封邮件都有一个MessageNumber，可以通过邮件的MessageNumber在收件箱里面取得该邮件
        }
        try {
            if (folder != null)
                folder.close(true);
            if (store != null)
                store.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }

    /**
     * 解析综合数据
     * @param part
     * @throws Exception
     */
    private static void getAllMultipart(Part part) throws Exception{
        String contentType = part.getContentType();
        int index = contentType.indexOf("name");
        boolean conName = false;
        if(index!=-1){
            conName=true;
        }
        //判断part类型
        if(part.isMimeType("text/plain") && ! conName) {
            System.out.println((String) part.getContent());
        }else if (part.isMimeType("text/html") && ! conName) {
            System.out.println((String) part.getContent());
        }else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int counts = multipart.getCount();
            for (int i = 0; i < counts; i++) {
                //递归获取数据
                getAllMultipart(multipart.getBodyPart(i));
                //附件可能是截图或上传的(图片或其他数据)
                if (multipart.getBodyPart(i).getDisposition() != null) {
                    //附件为截图
                    if (multipart.getBodyPart(i).isMimeType("image/*")) {
                        InputStream is = multipart.getBodyPart(i)
                                .getInputStream();
                        String name = multipart.getBodyPart(i).getFileName();
                        String fileName;
                        //截图图片
                        if(name.startsWith("=?")){
                            fileName = name.substring(name.lastIndexOf(".") - 1,name.lastIndexOf("?="));
                        }else{
                            //上传图片
                            fileName = name;
                        }

                        FileOutputStream fos = new FileOutputStream("D:\\"
                                + fileName);
                        int len = 0;
                        byte[] bys = new byte[1024];
                        while ((len = is.read(bys)) != -1) {
                            fos.write(bys,0,len);
                        }
                        fos.close();
                    } else {
                        //其他附件
                        InputStream is = multipart.getBodyPart(i)
                                .getInputStream();
                        String name = multipart.getBodyPart(i).getFileName();
                        FileOutputStream fos = new FileOutputStream("D:\\"
                                + name);
                        int len = 0;
                        byte[] bys = new byte[1024];
                        while ((len = is.read(bys)) != -1) {
                            fos.write(bys,0,len);
                        }
                        fos.close();
                    }
                }
            }
        }else if (part.isMimeType("message/rfc822")) {
            getAllMultipart((Part) part.getContent());
        }
    }

    /**
     * 解析附件内容
     * @param part
     * @throws Exception
     */
    private static void getAttachmentMultipart(Part part) throws Exception{
        if(part.isMimeType("multipart/*")){
            Multipart multipart = (Multipart) part.getContent();
            int count = multipart.getCount();
            for (int i = 0; i < count; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                if(bodyPart.getDisposition()!=null){
                    InputStream is = bodyPart.getInputStream();
                    FileOutputStream fos=new FileOutputStream("路径+文件名");
                    int len=0;
                    byte[] bys=new byte[1024];
                    while((len=is.read(bys))!=-1){
                        fos.write(bys, 0, len);
                    }
                    fos.close();
                }
            }
        }

    }
    /**
     * 解析图片内容
     * @param part
     * @throws Exception
     */
    private static void getPicMultipart(Part part) throws Exception{
        if(part.isMimeType("multipart/*")){
            Multipart multipart = (Multipart) part.getContent();
            int count = multipart.getCount();
            for (int i = 0; i < count; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                if(bodyPart.isMimeType("image/*")){
                    InputStream is = bodyPart.getInputStream();
                    FileOutputStream fos=new FileOutputStream("路径+文件名");
                    int len=0;
                    byte[] bys=new byte[1024];
                    while((len=is.read(bys))!=-1){
                        fos.write(bys, 0, len);
                    }
                    fos.close();
                }
            }
        }
    }
    /**
     * 解析文本内容
     * @param part
     * @throws Exception
     */
    private static void getTextMultipart(Part part) throws Exception{
        if(part.isMimeType("text/html")){
            String content = (String) part.getContent();
            System.out.println(content);
        }else if(part.isMimeType("text/plain")){
            String content = (String) part.getContent();
            System.out.println(content);
        }
    }


}